//
//  VistaPicoYPlaca.m
//  Pico y placa
//
//  Created by Mario Franco on 12/10/12.
//  Copyright (c) 2012 Mario Franco. All rights reserved.
//

#import "VistaPicoYPlaca.h"
#import "SessionManager.h"
#import "SubvistaPicoYPlaca.h"
#import "VistaEditarPicoYPlaca.h"
#import "TipoVehiculo.h"
#import "Regla.h"
#import <QuartzCore/QuartzCore.h>


@interface VistaPicoYPlaca ()
{
    SessionManager * principal;
}
@end

@implementation VistaPicoYPlaca
@synthesize subvista1;
@synthesize container;
@synthesize pageController;
@synthesize scroller;
@synthesize btnCompartir;
@synthesize btnAjustes;
@synthesize btnInfo;
@synthesize bannerView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    principal = [SessionManager darInstancia];

    [self moveBannerViewOffscreen];
    
    //Pintar el scroller
    scroller.delegate = self;    
    scroller.pagingEnabled = YES;
    
    //Es iPad        
    if([[UIDevice currentDevice].model rangeOfString:@"iPad"].location != NSNotFound)
    {
        btnCompartir.hidden = YES;
        //scroller.contentSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width*[principal.darFavoritos count], 747);
    }
    
    else
    {
        //Es iPhone 5
        if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 1136)))
        {
            CGRect containerRect = CGRectMake(0, 70, 320, 349);
            container.frame = containerRect;
            
            CGRect scrollerRect = CGRectMake(0, 70, 320, 349);
            scroller.frame = scrollerRect;
            
            CGRect pageRect = CGRectMake(38, 417, 245, 36);
            pageController.frame = pageRect;
            
            scroller.contentSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width*[principal.darFavoritos count], 349);
        }
        
        //Es otro iPhone
        else
        {
            scroller.contentSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width*[principal.darFavoritos count], 349);
        }     
    }

    pageController.numberOfPages = [[principal darFavoritos] count];
    
    //Llenar el scroller
    for (int i=0; i<[[principal darFavoritos] count]; i++)
    {
        SubvistaPicoYPlaca * controlador = [[SubvistaPicoYPlaca alloc]init];
        controlador.tipoVehiculo = [[principal darFavoritos] objectAtIndex:i];
        
        NSString *deviceType = [UIDevice currentDevice].model;
        
        //Es iPad
        if([deviceType rangeOfString:@"iPad"].location != NSNotFound)
        {
            [controlador pintarPlacaIPad];
            [controlador view].frame = CGRectMake(i*[[UIScreen mainScreen] bounds].size.width, 0, [[UIScreen mainScreen] bounds].size.width, 747);
        }
        
        //Es iPhone
        else
        {
            [controlador pintarPlacaIPhone];
            [controlador view].frame = CGRectMake(i*[[UIScreen mainScreen] bounds].size.width, 0, [[UIScreen mainScreen] bounds].size.width, 349);
        }        
        
        [self addChildViewController:controlador];    
        [scroller addSubview:[controlador view]];
    }    
    
    if([[principal darFavoritos] count]>0)
    {     
        //Pintar de primera la subvista correspondiente al tipo de vehículo favorito
        BOOL termino = false;
        for (int i=1; i<[[self childViewControllers] count] && !termino; i++)
        {
            SubvistaPicoYPlaca *controlador = [[self childViewControllers] objectAtIndex:i];
            if([controlador.tipoVehiculo isEqual:[principal darFavorito]])
            {
                pageController.currentPage = i-1;
                scroller.contentOffset = CGPointMake([[UIScreen mainScreen] bounds].size.width*(i-1),0);
                termino=true;
            }
        }
        
        if(!termino)
            pageController.currentPage = 0;
        
        int pagina = scroller.contentOffset.x /scroller.frame.size.width;
        SubvistaPicoYPlaca *controlador = [[self childViewControllers] objectAtIndex:pagina+1];
        
        if([controlador calcularPosicionDeHoy] == -1)
            btnCompartir.enabled = NO;
        else
            btnCompartir.enabled = YES;
    }
    
    else
    {
        btnCompartir.hidden = YES;
        btnAjustes.hidden = YES;
        btnInfo.hidden = YES;
    }
    
}

-(void)viewDidAppear:(BOOL)animated
{
    
    [NSThread detachNewThreadSelector:@selector(actualizarTablasLocales) toTarget:principal withObject:nil];
    
    //Redirigir a otra vista si no hay TipoVehiculo favoritos
    if([principal.darFavoritos count]==0)
       [self performSegueWithIdentifier:@"editarPicoYPlaca" sender:self];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int pagina = scrollView.contentOffset.x /scrollView.frame.size.width;
    pageController.currentPage = pagina;
    
    //Establecer nuevo favorito
    SubvistaPicoYPlaca *controlador = [[self childViewControllers] objectAtIndex:pagina+1];
    [principal establecerFavorito:controlador.tipoVehiculo];
    
    if([controlador calcularPosicionDeHoy] == -1)
        btnCompartir.enabled = NO;
    else
        btnCompartir.enabled = YES;
}

- (IBAction)clickPageController:(id)sender
{    
    int pagina = pageController.currentPage;
    
    CGRect frame = scroller.frame;
    frame.origin.x = frame.size.width * pagina;
    frame.origin.y = 0;
    
    [scroller scrollRectToVisible:frame animated:YES];
}

- (IBAction)mostrarAcciones:(id)sender
{
    int pagina = scroller.contentOffset.x /scroller.frame.size.width;
    SubvistaPicoYPlaca *controlador = [[self childViewControllers] objectAtIndex:pagina+1];
    
    //Screenshot de scroller
    UIImage* imagenScroller = nil;
    
    UIGraphicsBeginImageContextWithOptions(scroller.contentSize, scroller.opaque, 0.0);
    {
        CGPoint savedContentOffset = scroller.contentOffset;
        CGRect savedFrame = scroller.frame;
        
        scroller.contentOffset = CGPointZero;
        scroller.frame = CGRectMake(0, 0, scroller.contentSize.width, scroller.contentSize.height);
        
        [scroller.layer renderInContext: UIGraphicsGetCurrentContext()];
        imagenScroller = UIGraphicsGetImageFromCurrentImageContext();
        
        scroller.contentOffset = savedContentOffset;
        scroller.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    pageController.currentPage = pagina;
    [principal establecerFavorito:controlador.tipoVehiculo];
    
    //Crop
    CGRect cropRect;
    CGImageRef imagenCropRef;
    UIImage *imagenCrop;
    
    //Es iPhone 5 o iPhone retina 
    if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 1136)) || CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 960)))
    {
        cropRect = CGRectMake(pagina*self.view.frame.size.width*2+5, 25, self.view.frame.size.width*2-7, self.view.frame.size.height*2-10);
    }
    
    
    //Es otro iPhone
    else if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(320, 480)))
    {
        cropRect = CGRectMake(pagina*self.view.frame.size.width, 14, self.view.frame.size.width, self.view.frame.size.height*2-5);
    }
    
    //Es iPad retina
    else if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(1536, 2048)))
    {
        cropRect = CGRectMake(pagina*self.view.frame.size.width*2+173, 0, self.view.frame.size.width*2-346, self.view.frame.size.height*2);
    }

    //Es otro iPad
    else if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(768, 1024)))
    {
        cropRect = CGRectMake(pagina*self.view.frame.size.width+86, 0, self.view.frame.size.width-172, self.view.frame.size.height*2);
    }    

    imagenCropRef = CGImageCreateWithImageInRect(imagenScroller.CGImage, cropRect);
    imagenCrop = [UIImage imageWithCGImage:imagenCropRef scale:imagenScroller.scale orientation:imagenScroller.imageOrientation];    

    //Mensaje    
    
    NSMutableString *cadena = [NSMutableString stringWithString:@""];
    [cadena appendFormat:@"%@", [controlador formatearFecha:[NSDate date]]];
    [cadena appendFormat:@". "];
    [cadena appendFormat:@"%@", [[controlador.tipoVehiculo.reglas objectAtIndex:[controlador calcularPosicionDeHoy]] numeros]] ;
    [cadena appendFormat:@" #picoyplaca #"];
    [cadena appendString:[controlador.tipoVehiculo.ciudad.nombre stringByReplacingOccurrencesOfString:@" " withString:@""]];
    [cadena appendString:@" #"];
    [cadena appendString:[controlador.tipoVehiculo.tipo stringByReplacingOccurrencesOfString:@" " withString:@""]];    
    [cadena appendFormat:@". Descarga P&P Colombia para iOS en el App Store."];
    
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems: @[cadena, imagenCrop] applicationActivities:nil];
    activityViewController.excludedActivityTypes = @[UIActivityTypePostToWeibo, UIActivityTypeAssignToContact];
    [self presentViewController:activityViewController animated:YES completion:nil];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"editarPicoYPlaca"])
    {
        VistaEditarPicoYPlaca * vista = [segue destinationViewController];
        vista.primeraVez = YES;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)moveBannerViewOffscreen
{
    //Hacer que la subvista1 ocupe el espacio dejado por el bannerView
    CGRect frameOriginalSubvista1 = subvista1.frame;
    CGFloat nuevoHeight = self.view.frame.size.height;
    CGRect frameNuevoSubvista1 = frameOriginalSubvista1;
    frameNuevoSubvista1.size.height = nuevoHeight;
    
    //Posicionar el bannerView debajo de la subvista1 (offscreen)
    CGRect frameNuevoBanner = bannerView.frame;
    frameNuevoBanner.origin.y = nuevoHeight;
    
    subvista1.frame = frameNuevoSubvista1;
    bannerView.frame = frameNuevoBanner;
 }

-(void)moveBannerViewOnscreen
{
    CGRect frameNuevoBanner = bannerView.frame;
    frameNuevoBanner.origin.y = self.view.frame.size.height - frameNuevoBanner.size.height;
    
    CGRect frameOriginalSubvista1 = subvista1.frame;
    CGFloat nuevoHeight = self.view.frame.size.height - frameNuevoBanner.size.height;
    CGRect frameNuevoSubvista1 = frameOriginalSubvista1;
    frameNuevoSubvista1.size.height = nuevoHeight;
    
    [UIView beginAnimations:@"BannerViewIntro" context:NULL];
    subvista1.frame = frameNuevoSubvista1;
    bannerView.frame = frameNuevoBanner;
    [UIView commitAnimations];
}

-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    [self moveBannerViewOffscreen];
}

-(void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    [self moveBannerViewOnscreen];
}

- (void) viewWillDisappear:(BOOL)animated
{
    [bannerView removeFromSuperview];
    bannerView.delegate = nil;
    bannerView = nil;
}

@end
